let db              = require('../db/dbmanager');
const constants     = require('../data/constants');
const log4js        = require('../data/log');
const logger        = log4js.getLogger('db');
var format          = require('string-format');

/**
 * 设备表操作
 */
let Device = {
    cache: null,
    /**
     * 插入数据
     * @param {*} data ["testdevice",false]
     */
    insert: function(data,callback){
        if(!data.deviceid){
            callback(null);
            return;
        }
        let param ={
            $deviceid:data.deviceid,
            $password:data.password,
            $online  :data.online,
            $last_heart: (new Date()).getTime()
        };
        const sql = "insert into DEVICE(deviceid,password,online,last_heart) values($deviceid,$password,$online,$last_heart)";

        db.sqliteDB.run(sql,param);
        Device.cache = null;
        db.sqliteDB.lastRow("DEVICE",(d)=>{
            callback(d);
        });
    },
    /**
     * 更新内容,newdata的属性有; online,deviceid,sip_command_host,sip_command_port,sumnum,version,device_type,last_heart
     * @param {*} newdata 
     */
    update: function(newdata,callback){
        let sqldata={
            $deviceid: newdata.deviceid
        };
        
        let newsql='';
        if(newdata.online){
            sqldata.$online = newdata.online;
            if(newsql)newsql+=',';
            newsql += "online=$online";
        }
        if(newdata.sip_command_host){
            sqldata.$sip_command_host = newdata.sip_command_host;
            if(newsql)newsql+=',';
            newsql += "sip_command_host=$sip_command_host";
        }
        if(newdata.sip_command_port){
            sqldata.$sip_command_port = newdata.sip_command_port;
            if(newsql)newsql+=',';
            newsql += "sip_command_port=$sip_command_port";
        }
        if(newdata.sumnum){
            sqldata.$sumnum = newdata.sumnum;
            if(newsql)newsql+=',';
            newsql += "sumnum=$sumnum";
        }
        if(newdata.version){
            sqldata.$version = newdata.version;
            if(newsql)newsql+=',';
            newsql += "version=$version";
        }
        if(newdata.device_type){
            sqldata.$device_type = newdata.device_type;
            if(newsql)newsql+=',';
            newsql += "device_type=$device_type";
        }
        
        if(newdata.device_name){
            sqldata.$device_name = newdata.device_name;
            if(newsql)newsql+=',';
            newsql += "device_name=$device_name";
        }
        if(newdata.last_heart){
            sqldata.$last_heart=newdata.last_heart;
            if(newsql)newsql+=',';
            newsql += "last_heart=$last_heart";
        }
        if(newdata.server_id){
            sqldata.$server_id=newdata.server_id;
            if(newsql)newsql+=',';
            newsql += "server_id=$server_id";
        }
        if(newdata.rtsp_url){
            sqldata.$rtsp_url=newdata.rtsp_url;
            if(newsql)newsql+=',';
            newsql += "rtsp_url=$rtsp_url";
        }
        if(newdata.protocol){
            sqldata.$protocol=newdata.protocol;
            if(newsql)newsql+=',';
            newsql += "protocol=$protocol";
        }
        const sql = "update DEVICE set " + newsql + " where deviceid=$deviceid";
        db.sqliteDB.run(sql,sqldata);
        Device.cache = null;
        if(callback){
            callback(newdata);
        }
    },
    /**
     * 删除设备信息，同时删除子通道
     */
    del: function(deviceid){
        let param={
            $deviceid: deviceid
        };
        const sql = "DELETE FROM DEVICE WHERE deviceid=$deviceid";
        db.sqliteDB.run(sql,param);
        const sqlChannel="DELETE FROM CHANNEL WHERE parentid = $parentid";
        let paramChannel = {$parentid: deviceid};
        db.sqliteDB.run(sqlChannel,paramChannel);
        Device.cache = null;
    },
    /**
     * 
     * @param {string} deviceid 通道号
     * @param {*} callback 
     */
    getDeviceByDeviceId:async function(deviceid){
        if(!Device.cache){
            await Device.reloadCache();
        }
        let p = new Promise(function(resolve, reject){
            let item = Device.cache.find((value,index, arr) => {
                return value.deviceid == deviceid;
            });
            resolve(item);
        });
        return p;
    },
    /**
     * 设备设置的在线状态
     * @param {*} deviceid 
     * @param {*} callback 
     */
    updateOnline:async function(deviceid,online,callback){
        let ret = await Device.getDeviceByDeviceId(deviceid);

        constants.registry[deviceid].online=online;
        if(online){
            constants.registry[deviceid].last_heart=(new Date()).getTime();
        }
        
        if(ret){
            Device.update(constants.registry[deviceid],(d)=>{
                Device.cache = null;
                if(callback){
                    callback(deviceid);
                }
            });
        }else{
            Device.insert(constants.registry[deviceid],(d)=>{
                Device.cache = null;
                if(callback){
                    callback(deviceid);
                }
            });
            }
    },
    reloadCache: function(){
        let p = new Promise(function(resolve, reject){
            if(!Device.cache){
                const sql = "SELECT * from DEVICE order by deviceid DESC";
                db.sqliteDB.queryData(sql, function(rows){
                    Device.cache = Object.assign(rows);
                    resolve(Device.cache);
                });
            }else{
                resolve(Device.cache);
            }
        });
        return p;
    },
    /**
     * 查询列表
     * @param {*} page 第几页
     * @param {*} size 每页大小
     */
    list: function(page, size, device){
        let p = new Promise(function(resolve,reject){
            let sql = "SELECT * FROM DEVICE ";
            let data;
            if(device){
                sql += " WHERE deviceid LIKE ? OR device_name LIKE ?";
                data = ['%' +device + '%', '%' +device + '%',];
            }else{
                data = [];
            }
            sql += format(" order by deviceid DESC limit {0} offset {0}*{1}", size, page);
            db.sqliteDB.all(sql, data, function(err, rows){
                resolve(rows);
            });
        });
        return p;
    },
    count: function(device){
        let p = new Promise(function(resolve,reject){
            let sql = "SELECT COUNT(*) as c FROM DEVICE ";
            let data;
            if(device){
                sql += " WHERE deviceid LIKE ? OR device_name LIKE ?";
                data = ['%' +device + '%', '%' +device + '%',];
            }else{
                data = [];
            }
            db.sqliteDB.all(sql,data,(err, ret)=>{
                resolve(ret[0].c)
            });
        });
        return p;
    },
    // TODO: 重置状态，device的可能要修改
    reset:function(){
        let minTime = (new Date()).getTime()-60*10*1000;
        let sql = "UPDATE DEVICE SET online=0 WHERE last_heart < " + minTime;
        db.sqliteDB.run(sql);
        Device.cache = null;
    }
};

module.exports = Device;